package com.wchat.server;

import com.wchat.server.handler.WsChildHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;

/**
 * @author : willian fu
 * @date : 2021/8/19
 */
@Slf4j
@Component
public class ServerComponent {

    private final static int port = 8083;

    @Autowired
    private WsChildHandler wsChildHandler;

    private NioEventLoopGroup bossGroup;

    private NioEventLoopGroup workerGroup;


    public void initialize() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();
    }

    @PreDestroy
    public void destroy() {
        log.info("正在关闭设备网络服务😭 😥");
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

    public void stater() {
        ServerBootstrap bootstrapServer = new ServerBootstrap();
        bootstrapServer.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class);
        try {
            bootstrapServer.childHandler(wsChildHandler);
            bootstrapServer.bind(port);

            log.info("-----------------------------^o^-----------------------------------");
            log.info("网络服务已启动------->  WS端口=>{}", port);
            log.info("-------------------------------------------------------------------");
        }catch (Exception e){
            log.info("设备网络服务启动异常[{}]，请检查", e.getMessage());
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

}
